import styles from "./index.module.less";
import { Button, message, Modal, Tree, Typography, Space } from "antd";
import { useRef, useState, useEffect } from "react";
import SuperTable from "@/components/SuperTable";
import { getTableColumns } from "./constant";
import { cloneDeep, omit } from "lodash";
import { getAuthByRole, getMenuTreeList } from "@/api/modules/system";
import { PlusOutlined } from '@ant-design/icons';
import { useRequest } from "ahooks";
import { RESULT_CODES } from "@/api/helper/ResultCode";
const { Title, Text } = Typography;

interface Props {
    parentRow: object | null;
    visible: boolean;
    onCloseAuth: () => void;
    onSave: (checkedKeys: any) => void;
}


export default (props: Props) => {
    const {
        parentRow, visible, onSave, onCloseAuth
    } = props;
    const [authList, setAuthList] = useState([])
    const [initSelectedKeys, setInitSelectedKeys] = useState([])
    const [selectedKeys, setSelectedKeys] = useState<any []>(initSelectedKeys);
    const [checkedKeys, setCheckedKeys] = useState<any []>(initSelectedKeys);
    const [expandedKeys, setExpandedKeys] = useState<any []>([]);
    const [autoExpandParent, setAutoExpandParent] = useState(true);

    // 初始化展开所有节点
    useEffect(() => {
        if (visible) {
            getAuthByRole({id: parentRow?.id}).then((res1: any) => {
                if(res1.code === RESULT_CODES.SUCCESS) {
                    const result: any[] = flattenTreeData(res1?.data)
                    setInitSelectedKeys(result)
                    getMenuTreeList({}).then((res: any) => {
                        if(res.code === RESULT_CODES.SUCCESS) {
                            setAuthList(res?.data)
                            setSelectedKeys(result);
                            setCheckedKeys(result);

                            // const allKeys = flattenTreeData(res?.data);
                            // setExpandedKeys(allKeys.filter(key => key.includes('-')));
                        }
                    })
                }
            })
        }
    }, [visible]);

    // 处理树节点选择
    const onSelect = (selectedKeys: any, info: any) => {
        setSelectedKeys(selectedKeys);
    };

    // 处理树节点勾选
    const onCheck = (checkedKeys: any, info: any) => {
        setCheckedKeys(checkedKeys);
    };

    // 处理展开/收起
    const onExpand = (expandedKeys: any) => {
        setExpandedKeys(expandedKeys);
        setAutoExpandParent(false);
    };

    // 处理保存
    const handleSave = () => {
        if (checkedKeys.length === 0) {
            message.warning('请至少选择一个权限');
            return;
        }

        onSave(checkedKeys);
    };

    // 处理全选
    const selectAll = () => {
        const allKeys = flattenTreeData(authList);
        setCheckedKeys(allKeys);
    };

    // 处理清空
    const clearAll = () => {
        setCheckedKeys([]);
    };

    // 将树形数据转换为平铺结构，用于回显选中状态
    const flattenTreeData = (treeData: any) => {
        const result: any[] = [];

        const flatten = (nodes: any) => {
            nodes && nodes.forEach((node: any) => {
                result.push(node.id);
                if (node.children) {
                    flatten(node.children);
                }
            });
        };

        flatten(treeData);
        return result;
    };

    const handleCloseAuth = () => {
        onCloseAuth && onCloseAuth();
    }

    return (
        <Modal
            title={`配置权限`}
            open={visible}
            centered
            onCancel={handleCloseAuth}
            width={800}
            footer={[
                <Button key="selectAll" onClick={selectAll}>全选</Button>,
                <Button key="clearAll" onClick={clearAll}>清空</Button>,
                <Button key="cancel" onClick={onCloseAuth}>取消</Button>,
                <Button key="submit" type="primary" onClick={handleSave}>保存权限</Button>
            ]}
        >
            <Tree
                checkable
                selectable={false}
                onExpand={onExpand}
                expandedKeys={expandedKeys}
                autoExpandParent={autoExpandParent}
                onCheck={onCheck}
                checkedKeys={checkedKeys}
                onSelect={onSelect}
                selectedKeys={selectedKeys}
                treeData={authList}
                style={{ padding: '8px' }}
                fieldNames={{
                    key: 'id',          // 指定key字段
                    title: 'name',      // 指定标题字段
                    children: 'children',  // 指定子节点字段
                }}
            />
        </Modal>
    )
};